import router from './router/'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import useUserStore from "@/stores/useUserStore";
import useCommonStore from "@/stores/useCommonStore";
import useRouterStore from "@/stores/useRouterStore";

NProgress.configure({showSpinner: false});
const lockPage = '/lock'; //锁屏页

router.beforeEach((to, from, next) => {
    const meta = to.meta || {};
    const isMenu = meta.menu === undefined ? to.query.menu : meta.menu;
    const userStore = useUserStore()
    const commonStore = useCommonStore();
    const routerStore = useRouterStore();
    const token = userStore.token;
    commonStore.setIsMenu(isMenu === undefined)

    if (meta.isAuth === false) {
        next();
        return;
    }
    if (!token) {
        next('/login')
        return;
    }

    if (commonStore.isLock && to.path !== lockPage) { //如果系统激活锁屏，全部跳转到锁屏页
        next({path: lockPage})
        return;
    }
    if (to.path === '/login') { //如果登录成功访问登录页跳转到主页
        next({path: '/'})
        return;
    }
    //如果用户信息为空则获取用户信息，获取用户信息失败，跳转到登录页
    if (userStore.roles.length === 0) {
        userStore.GetUserInfo().then(() => {
            next({...to, replace: true})
        }).catch((e) => {
            console.log("注销登录",e)
            return userStore.FedLogOut();
        }).then(res => {
            next({path: '/login'})
        })
        return;
    }
    const toMeta = to.meta || {}
    const query = to.query || {}
    if (toMeta.target) {
        window.open(query.url.replace(/#/g, "&"))
        return
    } else if (toMeta.isTab !== false) {
        routerStore.addTag({
            name: query.name || to.name,
            path: to.path,
            fullPath: to.fullPath,
            params: to.params,
            query: to.query,
            meta: toMeta
        })
    }
    next()

})

router.afterEach(to => {
    NProgress.done();
    const commonStore = useCommonStore();
    let title = router.$avueRouter.generateTitle(to)
    router.$avueRouter.setTitle(title);
    commonStore.setIsSearch(false)
});
